import axios from "axios";


const fileAxios = axios.create({
    responseType:'arraybuffer'
})

/**
 * 请求拦截器
 */
fileAxios.interceptors.request.use(config => {
    // 如果存在token，则让后续每个接口都携带token
    if (window.sessionStorage.getItem("token")) {
        config.headers['Authorization'] = window.sessionStorage.getItem("token")
    }
    return config;
},error => {
    console.log(error)
})

fileAxios.interceptors.response.use(resp => {
    const headers = resp.headers;
    // 正则匹配
    let reg = RegExp(/application\/json/)
    // 是正常数据
    if (headers['content-type'].match(reg)) {
        resp.data = unitToString(resp.data);
    }else {
        // 文件流数据
        let fileDownload = require('js-file-download');
        let fileName = headers['content-disposition'].split(';')[1].split('filename=')[1];
        let contentType = headers['content-type'];
        fileName = decodeURIComponent(fileName);
        fileDownload(resp.data,fileName,contentType);
    }
})


/**
 * 解析成字符串
 * @param array
 * @returns {any}
 */
function unitToString(array) {
    let encodedString = String.fromCharCode.apply(null,new Uint8Array(array));
    let decodedString = decodeURIComponent(escape(encodedString));
    return JSON.parse(decodedString)
}



let base = '';
export const downloadRequest = (url,params) => {
    return fileAxios({
        methods:'get',
        url:`${base}${url}`,
        data:params
    })
}


export default fileAxios;





